package com.yhq.yhqproject.base.modules.board.repo;

import com.yhq.yhqproject.base.common.utils.ObjUtil;
import com.yhq.yhqproject.base.modules.board.entity.TemplateHistory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Map;

@Repository
public class TemplateHistoryRepo {
    @Resource
    private MongoTemplate mongoTemplate;

    public void add(TemplateHistory s) {
        mongoTemplate.save(s);
    }

    public void update(TemplateHistory s) {
        Update update = new Update();
        Map<String, Object> map = ObjUtil.beanAttrToMapKV(s);
        for (Map.Entry<String, Object> e : map.entrySet()) {
            if ("id".equals(e.getKey())) {
                continue;
            }
            update.set(e.getKey(), e.getValue());
        }
        if (s.getParams() != null && s.getParams().size() > 0) {
            update.set("params", s.getParams());
        }
        mongoTemplate.updateFirst(new Query(Criteria.where("id").is(s.getId())), update, TemplateHistory.class);
    }

    public void delete3DayAgo() {
        Long end = System.currentTimeMillis() - 3 * 24 * 3600 * 1000;
        Query query = new Query(Criteria.where("createTime").lt(end));
        mongoTemplate.remove(query, TemplateHistory.class);
    }

}
